<template>
  <div style="width: 300px; margin: 0 auto; padding: 20px; border: 1px solid #ccc; border-radius: 5px;">
    <h2 style="text-align: center;">登录</h2>
    <div>
      <label for="username">用户名：</label>
      <input type="text" id="username" v-model="username" placeholder="请输入用户名"
             style="width: 150px;margin: 0 auto"/>
    </div>
    <div>
      <label for="password">密码：</label>
      <input type="password" id="password" v-model="password" placeholder="请输入密码"
             style="width: 150px;margin: 0 auto"/>
    </div>
    <button @click="login"
            style="width: 100%; margin-top: 10px; padding: 5px; background-color: #007bff; color: white; border: none; border-radius: 3px;">
      登录
    </button>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import axios from 'axios';
import {useRouter} from 'vue-router';

const username = ref('');
const password = ref('');
const router = useRouter();

const login = async () => {
  const params = new URLSearchParams();
  params.append('username', username.value);
  params.append('password', password.value);

  axios.post('http://127.0.0.1:8000/login/', params.toString(), {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
      .then(response => {
        localStorage.setItem("jwt", response.data.access);
        router.push('/home');
      })
      .catch(error => {
        if (error.response.status === 401 || error.response.status === 403) {
          // 清除本地存储的token
          localStorage.removeItem('jwt');
          // 重定向到登录页面
          window.location.href = '/login';
        }
        console.error(error);
      });
};
</script>

<style scoped>
/* 可以在这里添加更多样式规则，当前scoped表示样式只作用于当前组件 */
</style>